package com.ssm.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanMap;

import java.math.BigInteger;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Map;

@Slf4j
public class ToBean {
    public static <T> T toBean(Map map, Class<T> clazz) {
        T bean = null;
        try {
            bean = clazz.getDeclaredConstructor().newInstance();
            BeanMap beanMap = BeanMap.create(bean);

            beanMap.keySet().stream().forEach(paramName -> {
                Object value = map.get(paramName);
                if (value != null) {
                    Class<?> paramType = beanMap.getPropertyType((String) paramName);

                    // Integer、BigInteger转Long
                    if (paramType.equals(Long.class) && value instanceof Integer) {

                        // 若map中的数据类型为Integer、而对象中相应的数据类型为Long时:
                        value = ((Integer) value).longValue();

                    } else if (paramType.equals(Long.class) && value instanceof BigInteger) {

                        // 若map中的数据类型为BigInteger、而对象中相应的数据类型为Long时
                        value = ((BigInteger) value).longValue();
                    }

                    // Long型纯数字时间戳转LocalDateTime
                    if (paramType.equals(LocalDateTime.class) && value instanceof Long) {
                        value = Instant.ofEpochMilli((Long) value).atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
                    }

                    beanMap.put(paramName, value);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
}

}
